﻿using Microsoft.SharePoint.Administration;

namespace ServBus.ListForm2010.Resources
{
    public class ResourceUtility
    {
        private static readonly string WEBCONFIG_OWNER = "ListForm 2010";
        private static readonly string RESOURCE_PREFIX = "SBIBLF2010Resources";
        private static readonly string ASSEMBLY_NAME = "ServBus.ListForm2010.Resources.ResourceExpressionBuilder, ServBus.ListForm2010, Version=1.0.0.0, Culture=neutral, PublicKeyToken=df5827f77359eb0a";

        public static void InstallToWebConfig(SPWebApplication webapp)
        {
           
            
            SPWebConfigModification wcm = new SPWebConfigModification(
                string.Format("add[@expressionPrefix=\'{0}\'][@type=\'{1}\']", RESOURCE_PREFIX, ASSEMBLY_NAME),
                "configuration/system.web/compilation/expressionBuilders");
            wcm.Owner = WEBCONFIG_OWNER;
            wcm.Sequence = 0;
            wcm.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            wcm.Value = string.Format("<add expressionPrefix=\"{0}\" type=\"{1}\" />", RESOURCE_PREFIX, ASSEMBLY_NAME);
            if (!webapp.WebConfigModifications.Contains(wcm))
            {
                //Collection<SPWebConfigModification> wcms = webapp.WebConfigModifications;
                //foreach (SPWebConfigModification wcmper in wcms)
                //{
                //    if (wcmper.Owner == WEBCONFIG_OWNER)
                //    {
                //        webapp.WebConfigModifications.Remove(wcmper);
                //    }
                //}

                //webapp.WebConfigModifications.Clear();

                webapp.WebConfigModifications.Add(wcm);
                webapp.Update();
                webapp.WebService.ApplyWebConfigModifications();
            }
        }

        public static void RemoveFromWebConfig(SPWebApplication webapp)
        {
            SPWebConfigModification wcm = new SPWebConfigModification(
                string.Format("add[@expressionPrefix=\'{0}\'][@type=\'{1}\']", RESOURCE_PREFIX, ASSEMBLY_NAME),
                "configuration/system.web/compilation/expressionBuilders");
            wcm.Owner = WEBCONFIG_OWNER;
            wcm.Sequence = 0;
            wcm.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            wcm.Value = string.Format("<add expressionPrefix=\"{0}\" type=\"{1}\" />", RESOURCE_PREFIX, ASSEMBLY_NAME);
            if (webapp.WebConfigModifications.Contains(wcm))
            {
                webapp.WebConfigModifications.Remove(wcm);
                webapp.Update();
                webapp.WebService.ApplyWebConfigModifications();
            }
        }
    }
}
